package lex.explorer;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.ConsoleHandler;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;

import org.lex.utils.logging.LoggerConfigurationBuilder;
import org.lex.utils.logging.PatternFormatter;


public class Logs {
	private static final Level DEFAULT_LEVEL = Level.INFO;
	private static Level currentLevel = DEFAULT_LEVEL;
	private static final String ROOT = "lex.explorer";
	static {
		initializeLogger(new String[] { "-log", "ALL" });
	}

	public static Logger get(Object o) {
		if (null == o)
			return Logger.getLogger(ROOT);
		return Logger.getLogger(o.getClass().getName());
	}

	public static Level getLevel() {
		return currentLevel;
	}

	public static void initializeLogger(String[] args) {
		currentLevel = DEFAULT_LEVEL;
		if (args.length > 1) {
			for (int i = 0, n = args.length - 1; i < n; i++) {
				String arg = args[i];
				if (arg.equalsIgnoreCase("-log")) {
					try {
						currentLevel = Level.parse(args[i + 1].toUpperCase());
					} catch (Exception e) {
						System.err.println(e.getMessage());
						currentLevel = DEFAULT_LEVEL;
					}
					break;
				}
			}
		}
		doInitializeRootLogger(ROOT, currentLevel);
	}

	private static void doInitializeRootLogger(String name, Level level) {
		String handler = ConsoleHandler.class.getCanonicalName();
		Properties p = new Properties();
		// global setting
		p.setProperty(".level", DEFAULT_LEVEL.getName());
		p.setProperty("handlers", handler);
		p.setProperty(handler + ".level", level.getName());
		p.setProperty(handler + ".formatter", PatternFormatter.class.getCanonicalName());
		// root logger setting
		p.setProperty(name + ".level", level.getName());
		p.setProperty(name + ".handlers", handler);
		p.setProperty(name + ".useParentHandlers", "false");
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		try {
			p.store(out, "Logger configurations");
			ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
			LogManager.getLogManager().readConfiguration(in);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		LoggerConfigurationBuilder.setDebugMode(Level.ALL, PatternFormatter.class.getCanonicalName());
	}
}
